<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\zyhsapi\model;

use app\common\cachemodel\ArticleCommentReply;
use think\Cache;
use think\Config;
use XznsTools\cache\CacheManage;
use XznsTools\cache\zyhs\CacheManageZyhs;

/**
 * 消息中西相关模型
 * Class MessageCenter
 * @package app\common\model
 */
class ZyhsMessageCenter extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_message_center';
    public $cacheModel = 'user.message';

    /**
     * 消息中心添加消息
     * @param $uid
     * @param $messageData
     * @return bool
     */
    public function pushMessage($uid, $messageData)
    {
        try
        {
            $mid = $this->insertGetId($messageData);
            //用户消息列表缓存添加
            $this->listDataAdd((int)$uid, [$mid => $mid], 1);
            //用户未读消息缓存添加
            CacheManageZyhs::getInstance()->setCacheConfig('user.unread_message', $uid)->listAdd([$mid => $mid], $messageData['type']);
        }
        catch (\Exception $e)
        {
            \think\Log::write('写入消息中心失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return $mid;
    }

    /**
     * 更新消息数据
     * @param int $uid
     * @param array $ids
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function UpdateData(int $uid, array $ids, array $data)
    {
        try
        {
            $where = ['id' => ['in', $ids]];
            $this->where($where)->update($data);

            foreach ($ids as $id)
            {
                //删除用户未读消息缓存
                CacheManageZyhs::getInstance()->setCacheConfig('user.unread_message', $uid)->setListKeyType(1)->delJudge($id);
                //更新消息详情缓存
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write('更新用户消息失败:' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 删除消息
     * @param int $uid
     * @param array $ids
     * @param array $data
     * @return bool
     * @throws \Exception
     */
    public function DelData(int $uid, array $ids, array $data)
    {
        try
        {
            $where = ['id' => ['in', $ids]];
            $this->where($where)->update($data);
            //删除用户消息列表缓存
            $this->listDataDel($uid, $ids, 1);
            foreach ($ids as $id)
            {
                //删除用户未读消息缓存
                CacheManageZyhs::getInstance()->setCacheConfig('user.unread_message', $uid)->setListKeyType(1)->delJudge($id);
                //删除消息详情缓存
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write('删除用户消息失败:' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 获取用户所有未读消息id,用户一键已读
     * @param array $map [uid,type]
     * @return array|mixed
     * @throws \Exception
     */
    public function getAllUserMessage($map = [])
    {
        return $this->getUserUnreadMsg($map['uid'], $map['type']);
    }

    /**
     * 缓存分页获取用户消息
     * @param $uid
     * @param $type
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserMsg($uid, $type, int $page = 1)
    {
        $limit = $this->pageLimit ?: Config::get('paginate.list_rows');
        $data = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->setListKeyType($type)
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid, $type)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$uid, $type], $sortType);
                }
                // 没开启缓存
                return $this->getPaginateInData([$uid, $type], $sortType);
            }, 'id', [], 0, 'list', 'list_details');
        return $data;
    }

    /**
     * 获取所有用户未读的消息id
     * @param $uid
     * @param $type
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserUnreadMsg($uid, $type)
    {
        $mids = CacheManageZyhs::getInstance()->setCacheConfig('user.unread_message', $uid)
            ->setListKeyType($type)
            ->ZsGetIocData('list', function () use ($uid, $type)
            {
                return $this->getUserUnreadMsgFromDms($uid, $type);
            });
        return $mids;
    }

    /**
     * 数据库获取用户所有未读消息id
     * @param $uid
     * @param $type
     * @return array
     */
    public function getUserUnreadMsgFromDms($uid, $type)
    {
        // switch ($type)
        // {
        //     case 1:
        //         $where['type'] = 1;
        //         break;
        //     case 2:
        //         $where['type'] = 2;
        // }
        $where['range'] = [['=', $uid], ['=', 0], 'or'];
        $where['is_read'] = 0;

        try
        {
            $mid = $this
                ->where($where)
                ->column('id');
            $ids = [];
            foreach ($mid as $id)
            {
                $ids[$id] = $id;
            }
        }
        catch (\Exception $e)
        {
            $ids = [];// 消息列表默认为空
        }
        return $ids;
    }

    /**
     * 数据库批量获取消息
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {
            $where['id'] = ['in', $ids];
        } else
        {
            $where = ['range' => $type[0], 'status' => 0];
        }
        $field = 'id,status,is_read,range,type,reid,cid,title,content,link,target,create_time';
        try
        {
            $data = $this
                ->where($where)
                ->order('id', 'DESC')
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 数据库分页获取用户消息
     * @param array $map
     * @param string $sortType
     * @return array|void
     */
    public function getPaginateInData($map, $sortType)
    {
        $page = input('page', 1);
        try
        {
            $where = ['range' => $map[0], 'type' => $map[1], 'status' => 0];
            $field = 'id,status,is_read,range,type,reid,cid,title,content,link,target,create_time';
            try
            {
                $data = $this
                    ->alias('m')
                    ->where($where)
                    ->field($field)
                    ->order('id', 'DESC')
                    ->paginate(10, false, ['page' => $page])->toArray();
            }
            catch (\Exception $e)
            {
                $data = [];
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
